import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import { MenuItem } from './types'
// import { isValidToken } from './util/jwt'
import autoImport from './util/autoimport'

// 路由信息
const routes: Array<RouteRecordRaw> = [
  { path: '/', redirect: { path: '/home' } }
]

// 菜单信息
let menus: Array<MenuItem> = []

// 自动生成路由和菜单列表
const addRoutesAndMenus = () => {
  // 自动加载项目里全部模块的路由文件
  const moudulesRoutes = autoImport(
    require.context('./pages', true, /router.ts/)
  )

  // 将加载到的路由合并到 routes 中
  moudulesRoutes.forEach((item: any) => {
    routes.push(item)
  })

  menus = routes
    // 自生成需要权限验证的菜单
    .filter((route: RouteRecordRaw) => !route.meta || route.meta.auth == true)
    .map((route: RouteRecordRaw, index: number) => {
      return {
        id: index,
        name: (route.meta && (route.meta.title || route.name)) || route.name,
        path: route.path,
      } as MenuItem
    })
}

addRoutesAndMenus()

const router = createRouter({
  // history: createWebHistory(process.env.BASE_URL),
  history: createWebHashHistory(),
  routes,
})

// 路由的权限验证处理
// router.beforeEach((to, from, next) => {
//   if (to.meta.title) {
//     ;(window as any).document.title = to.meta.title
//   } else {
//     ;(window as any).document.title = (window as any).app.name
//   }
//   const token = localStorage.getItem('userToken')
//   const isAuthenticated = isValidToken(token as any)
//   if (!isAuthenticated && token) localStorage.removeItem('userToken')
//   if (to.name === 'Login' && isAuthenticated) next({ name: 'Home' })
//   else if (to.meta.auth && !isAuthenticated) next(`/login?backUrl=${from.path}`)
//   else next()
// })

export { router, menus }
